package com.pearl.controller;

import com.alibaba.fastjson.JSONObject;
import com.pearl.db.UserDao;
import com.pearl.entitys.beans.UserLoginData;
import com.pearl.entitys.beans.UserToken;
import com.pearl.entitys.dataBaseTable.User;
import com.pearl.Interface.JwtIgnore;
import com.pearl.responseEntity.Response;
import com.pearl.utils.db.PrimeDB;
import com.pearl.utils.JwtTokenUtil;
import java.sql.Connection;
import java.time.LocalDateTime;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class LoginController {

  @Autowired
  private PrimeDB primeDB;

  /**
   * 登录
   */

  @JwtIgnore
  @PostMapping("/login")
//  @ResponseBody
  public Response login(@RequestBody UserLoginData userDto, HttpServletResponse response)
      throws Exception {
    try (Connection conn = primeDB.create()) {
      //...参数合法性验证

      //从数据库获取用户信息

      //....用户、密码验证

      //创建token，并将token放在响应头
      UserToken userToken = new UserToken();
//      BeanUtils.copyProperties(dbUser, userToken);

      String token = JwtTokenUtil.createToken(JSONObject.toJSONString(userToken));
      response.setHeader(JwtTokenUtil.AUTH_HEADER_KEY, token);
      //定义返回结果
//      BeanUtils.copyProperties(dbUser, dbUser);

      UserDao userDao = new UserDao(conn);
      User user = new User();
      user.setUserId(userDto.getAccount());
      user.setUserName("111");
      user.setPassword("111");
      user.setEmail("121@aa.com");
      user.setPhone("111");
      user.setSalt("111");
      user.setAge(11);
      user.setSex("男");
      user.setStatus(1);
      user.setCreateTime(LocalDateTime.now());
      user.setUpdateTime(LocalDateTime.now());
      userDao.insert(user);

      return new Response<>(0, user, "成功");
    } catch (Exception e) {
      return new Response<>(1, e.getMessage());
    }
  }
}
